package top.gohigh.sxdial3;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by fupan on 2018/4/10.
 */

public class TPRouter {


    HttpURLConnection connection=null;

    public static  String securityEncode(String a,String c ,String b){

        String d="";
        int e,f,g,h,k=187;
        int m=187;
        f=a.length();
        g=c.length();
        h=b.length();
        e=f>g?f:g;
        for(int l=0;l<e;l++){
            m = k = 187;
            if(l>=f){
                m=c.charAt(l);
            }
            else{
                if(l>=g){
                    k=a.charAt(l);
                }else{
                    k=a.charAt(l);
                    m=c.charAt(l);
                }
            }
            d+=b.charAt((k^m)%h);

        }



        return  d;
    }


    public static String TPAdminPwdEncode(String pwd){
        return securityEncode(pwd, "RDpbLfCPsJZ7fiv", "yLwVl0zKqws7LgKPRQ84Mdt708T1qQ3Ha7xv3H7NyU84p21BriUWBU43odz3iP4rBL3cD02KZciXTysVXiV8ngg6vL48rPJyAUw0HurW20xqxv9aYb4M9wK1Ae0wlro510qXeU07kV57fQMc8L6aLgMLwygtc0F10a0Dg70TOoouyFhdysuRMO51yY5ZlOZZLEal1h0t9YQW0Ko7oBwmCAHoic4HYbUyVeU3sfQ1xtXcPcf1aT303wAQhv66qzW");
    }

    public  int Dial(String host, String router_pwd, byte[] acc, String psw) throws  Exception{

            host="http://"+host;
            String stok= login(host,router_pwd);
            if(stok==null||stok==""){
                //login error
                 return 1;
            }
            String setUrl=host+"/stok="+stok+"/ds";

            if(!set(setUrl,acc,psw)){
                //set error
                return 2;
            }

            return 0;




    }


    private boolean set(String url,byte[] acc,String pwd) throws  Exception{
        String username=escape(new String(acc));

        Log.v("code12",username);
        JSONObject pppoe=new JSONObject();
        pppoe.put("username",username);
        pppoe.put("password",pwd);
        JSONObject data=new JSONObject();

        JSONObject protocol=new JSONObject();
        JSONObject wan=new JSONObject();
        wan.put("wan_type","pppoe");

        protocol.put("wan",wan);
        protocol.put("pppoe",pppoe);
        data.put("protocol",protocol);
        data.put("method","set");
       Log.v("123",url);
       Log.v("123",data.toString());

        JSONObject result=ajaxPost(url,data);
        if(result.getInt("error_code")==0){
            return true;
        }

        return  false;
    }

    private String login(String host, String router_pwd) throws Exception{


        JSONObject data=new JSONObject();
        JSONObject login=new JSONObject();
        login.put("password",TPAdminPwdEncode(router_pwd));
        data.put("method","do");
        data.put("login",login);
        JSONObject result=ajaxPost(host,data);

        if(result.getInt("error_code")==0){
            return result.get("stok").toString();
        }

        return "";
    }


    private JSONObject ajaxPost(String url_str,JSONObject data) throws  Exception{
        URL url=new URL(url_str);
        HttpURLConnection connection=(HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        //ajax 请求头
        connection.setRequestProperty("X-Requested-With","XMLHttpRequest");

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(3000);
        OutputStream outputStream=connection.getOutputStream();
        outputStream.write(data.toString().getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
        if(connection.getResponseCode()!=200){
            JSONObject result=new JSONObject();
            result.put("error_code",connection.getResponseCode());
            return result;
        }
        InputStream inputStream=connection.getInputStream();
        String responseBody=new String(getBytesByInputStream(inputStream),"UTF-8");
        inputStream.close();

        JSONObject result=new JSONObject(responseBody);
        return result;
    }



    private static byte[] getBytesByInputStream(InputStream is) {
        byte[] bytes = null;
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        byte[] buffer = new byte[1024 * 8];
        int length = 0;
        try {
            while ((length = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, length);
            }
            bos.flush();
            bytes = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytes;
    }



    public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j))
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16)
                    tmp.append("0");
                tmp.append(Integer.toString(j, 16).toUpperCase());
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }




}
